require 'gosu'
require 'zindex'

class Map
  module Tokens
    GRASS='"'
    EARTH='#'
    CLOUD='c'
    GEM='x'
    PLAYER='p'
    BUG='b'
  end
  module Tiles
    GRASS = 0
    EARTH = 1
    CLOUD = 2
    
    SIZE=50
  end  
  attr_reader :width, :height, :gems, :filename, :player_x, :player_y
  
  def initialize(window)
    @window=window
    @filename=File.join(window.level_dir,"map.txt")
    @tileset = Image.load_tiles(window, File.join(window.level_dir,'tileset.png'), Tiles::SIZE, Tiles::SIZE, true)
    @sky = Image.new(window, File.join(window.level_dir,'sky.png'), true)
    @gem_img = Image.new(window, "#{cur_dir}/graphics/ruby_stone.png", false)
    @gems = []
    @horizontal_tiles=@window.width / Tiles::SIZE
    @vertical_tiles=@window.height / Tiles::SIZE
    load_from_file
  end

  def draw(screen_x, screen_y)    
    @sky.draw(0, 0, Zindex::BACKGROUND)
      
    first_x = screen_x / Tiles::SIZE 
    first_y = screen_y / Tiles::SIZE 
    last_x = first_x + 1 + @horizontal_tiles
    last_y = first_y + 1 + @vertical_tiles
      
    (first_y..last_y).each do |y|
      (first_x..last_x).each do |x|
        break unless @tiles[x]      
        tile = @tiles[x][y]
        if tile
          @tileset[tile].draw(x * Tiles::SIZE - screen_x, y * Tiles::SIZE - screen_y, Zindex::BACKGROUND)      
        end
      end
    end
    @gems.each { |c| c.draw(screen_x, screen_y) }
  end
  
  def load_from_file(draw_gems=true)
    lines = File.readlines(@filename).map { |line| line.chop }
      @height = lines.size
      @width = lines[0].size
      @tiles = Array.new(@width) do |x|
        Array.new(@height) do |y|
          case lines[y][x, 1].downcase
          when Tokens::GRASS
            Tiles::GRASS
          when Tokens::EARTH
            Tiles::EARTH
          when Tokens::CLOUD
            Tiles::CLOUD  
          when Tokens::GEM
            @gems.push(RubyStone.new(@gem_img, x,  y )) if draw_gems 
            nil
          when Tokens::PLAYER
             @player_x= x
             @player_y= y 
            nil
          else
            nil
          end
        end
      end  
  end
  
  def coords_of_tokens(token)
    lines = File.readlines(@filename).map { |line| line.chop }
    height = lines.size
    width = lines[0].size
    coords=Array.new
    width.times do |x|
      height.times do |y|
        coords << [x,y] if lines[y][x, 1].downcase == token         
      end
    end
    coords
  end
    
  # Solid at a given pixel position?
  def solid?(x, y)
    tile=@tiles[x / Tiles::SIZE][y / Tiles::SIZE]
    y < 0 || tile==Tiles::EARTH || tile==Tiles::GRASS
  end
  
  def would_fit(cur_x, cur_y, offs_x, offs_y, x_padding=0, y_padding=0)
    # Check at the center/top and center/bottom for map collisions
     !solid?(cur_x + offs_x, cur_y + offs_y) && !solid?(cur_x + offs_x + x_padding, cur_y + offs_y + y_padding)     
  end
end
